from django.shortcuts import render,reverse
from django.http import HttpResponse,JsonResponse
from .. import models
from django.core.paginator import Paginator

# Create your views here.
def selectAllTypes():
    data = models.booktype.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    for x in data:
        num = x.path.count(',')-1
        x.sb = '|----'*num
        if x.pid != 0:
            x.pname = models.booktype.objects.get(id=x.pid).name
    return data

# 图书分类列表
def index(request):
    # 获取所有的图书分类
    # data = models.booktype.objects.all()
    data = selectAllTypes()
    # 分页类
    p = Paginator(data,5)

    inx_p = request.GET.get('page',1)
    # 获取当前页码数据
    userlist = p.get_page(inx_p)
    # 分配数据
    content = {'data':userlist,'contacts':userlist}
    return render(request,'myadmin/types/index.html',content)

# 图书分类 添加
def add(request):
    # 当前所有图书分类
    # data = models.booktype.objects.all()
    data = selectAllTypes()
    context = {'data':data}
    return render(request,'myadmin/types/add.html',context)

# 图书分类 执行添加
def insert(request):
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')

    if data['pid'] == '0':
        data['path'] = '0,'
    else:
        # 查询当前选择的父类的path
        path = models.booktype.objects.get(id=data['pid']).path
        data['path'] = path+data['pid']+','
    try:
        obj = models.booktype(**data)
        obj.save()
        url = reverse('myadmin_types_index')
        return HttpResponse(f'<script>alert("图书分类添加成功"); location.href="{url}"</script>')
    except:
        url = reverse('myadmin_types_add')
        return HttpResponse(f'<script>alert("图书分类添加失败"); location.href="{url}"</script>')

# 图书分类 删除
def delete(request):
    # 获取分类ID
    id = request.GET.get('id')

    # 判断当前类下是否存在
    num = models.booktype.objects.filter(pid=id).count()
    if not num:
        return JsonResponse({'code':1,'msg':'当前分类下还有子类，不能删除'})
    # if goodsnum:
    #     return JsonResponse({'code':2,'msg':'当前分类下还有书籍发布，不能删除'})
    try:
        # 获取当前的父类对象
        obj = models.booktype.objects.get(id = id)
        obj.delete()
        return JsonResponse({'code':0,'msg':'删除成功'})
    except:
        return JsonResponse({'code':3,'msg':'删除失败'})

# 图书分类 编辑
def edit(request):
    try:
        id = request.GET.get('id')
        name = request.GET.get('name')
        obj = models.booktype.objects.get(id=id)
        obj.name = name
        obj.save()
        return JsonResponse({'code':0,'msg':'更新成功'})
    except:
        return JsonResponse({'code':1,'msg':'更新失败'})
